const https = require('https');
const logger = require('../utils/logger');
const { version } = require('../package.json');
const fs = require('fs').promises;
const path = require('path');

// 版本检查配置
const CONFIG = {
  // Gitee API 地址
  VERSION_URL: 'https://gitee.com/api/v5/repos/yiweixingchen/querysystem/releases/latest',
  CACHE_FILE: path.join(__dirname, '../.version_cache'),
  CACHE_TTL: 24 * 60 * 60 * 1000
};

// 从 Gitee 获取最新版本信息
async function fetchLatestVersion() {
  return new Promise((resolve, reject) => {
    const req = https.get(CONFIG.VERSION_URL, {
      headers: {
        'User-Agent': 'Certificate-System-Backend',
        'Accept': 'application/json'
      }
    }, (res) => {
      let data = '';
      
      res.on('data', chunk => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const releaseInfo = JSON.parse(data);
          // Gitee API 返回格式适配
          resolve({
            version: releaseInfo.tag_name.replace('v', ''),
            releaseDate: releaseInfo.created_at,
            description: releaseInfo.body,
            downloadUrl: releaseInfo.html_url,
            assets: releaseInfo.assets
          });
        } catch (error) {
          reject(new Error('解析版本信息失败: ' + error.message));
        }
      });
    });

    req.on('error', error => {
      reject(new Error('获取版本信息失败: ' + error.message));
    });

    req.end();
  });
}

// 检查本地缓存
async function checkVersionCache() {
  try {
    const cacheData = await fs.readFile(CONFIG.CACHE_FILE, 'utf8');
    const cache = JSON.parse(cacheData);
    
    if (Date.now() - new Date(cache.timestamp).getTime() < CONFIG.CACHE_TTL) {
      return cache.versionInfo;
    }
  } catch (error) {
    // 缓存不存在或无效，忽略错误
  }
  return null;
}

// 保存版本信息到缓存
async function saveVersionCache(versionInfo) {
  const cache = {
    timestamp: new Date().toISOString(),
    versionInfo
  };
  await fs.writeFile(CONFIG.CACHE_FILE, JSON.stringify(cache, null, 2));
}

// 比较版本号
function compareVersions(v1, v2) {
  const parts1 = v1.split('.').map(Number);
  const parts2 = v2.split('.').map(Number);
  
  for (let i = 0; i < 3; i++) {
    if (parts1[i] > parts2[i]) return 1;
    if (parts1[i] < parts2[i]) return -1;
  }
  return 0;
}

// 主检查函数
async function checkUpdate() {
  try {
    logger.info('正在检查更新...');
    logger.info('当前版本:', version);

    let latestVersion = await checkVersionCache();
    
    if (!latestVersion) {
      latestVersion = await fetchLatestVersion();
      await saveVersionCache(latestVersion);
    }

    const comparison = compareVersions(latestVersion.version, version);
    
    if (comparison > 0) {
      const updateInfo = {
        currentVersion: version,
        latestVersion: latestVersion.version,
        releaseDate: latestVersion.releaseDate,
        description: latestVersion.description,
        downloadUrl: latestVersion.downloadUrl,
        hasUpdate: true,
        assets: latestVersion.assets
      };
      
      logger.warn('发现新版本:', updateInfo);
      return updateInfo;
    } else {
      logger.info('当前已是最新版本');
      return { hasUpdate: false, currentVersion: version };
    }
  } catch (error) {
    logger.error('检查更新失败:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  checkUpdate()
    .then(updateInfo => {
      process.exit(updateInfo.hasUpdate ? 1 : 0);
    })
    .catch(() => {
      process.exit(2);
    });
} else {
  // 作为模块导出
  module.exports = checkUpdate;
} 